package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;


    @RequiredLog(operation = "查询用户信息")
    @Override
    public List<SysUser> findUsers(SysUser entity) {
        //return PageUtil.startPage().doSelectPageInfo(()->{sysUserDao.selectUsers(entity);});
        return sysUserDao.selectUsers(entity);
    }

    @Override
    public SysUser findById(Integer id) {
        SysUser user = sysUserDao.selectById(id);
        if (user==null)
            throw new ServiceException("没有找到对应的用户");
        List<Integer> roleIds = sysUserRoleDao.selectRoleIdsByUserId(id);
        user.setRoleIds(roleIds);
        return user;
    }

    @Override
    @Transactional(timeout = 5)
    public int saveUser(SysUser entity){
        String salt= UUID.randomUUID().toString();
        SimpleHash sh=new SimpleHash("MD5",entity.getPassword(),salt,1);
        String hashedPassword=sh.toHex();
        entity.setSalt(salt);
        entity.setPassword(hashedPassword);
        int rows=sysUserDao.insertUser(entity);
        sysUserRoleDao.insertUserRoles(entity.getId(),entity.getRoleIds());
        return rows;
    }

    @Override
    public int updateUser(SysUser entity) {
        int rows=sysUserDao.updateUser(entity);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        sysUserRoleDao.deleteByUserId(entity.getId());
        sysUserRoleDao.insertUserRoles(entity.getId(),entity.getRoleIds());
        return rows;
    }
    /**
     * @RequiresPermissions 由shiro框架定义，基于此注解定义授权切入点方法，也就是说用户访问此方法时，需要授权才能访问。
     * shiro框架底层会基于登录用户获取登录用户权限（菜单的权限标识），然后判断用户权限中是否包含@RequiresPermissions
     * 注解中定义的权限标识
     */
    @RequiresPermissions("sys:user:update")
    @Override
    public int validById(Integer id, Integer valid) {
        int rows = sysUserDao.validById(id, valid, "admin");
        if (rows==0)
            throw new ServiceException("记录可能不存在");
        return rows;
    }
}
